package com.hmall.common.config;

import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnProperty(name = "spring.rabbitmq.listener.simple.retry.enabled", havingValue = "true")
@ConditionalOnClass(RabbitTemplate.class)
@RequiredArgsConstructor
public class MqConsumeErrorAutoConfiguration {
    private final RabbitTemplate rabbitTemplate;

    @Value("${spring.application.name}")
    private String SERVICE_NAME;

    @Bean
    public DirectExchange errorExchange(){
        return ExchangeBuilder.directExchange("error.direct").build();
    }

    @Bean
    public Queue errorQueue(){
        return QueueBuilder.durable(SERVICE_NAME + ".error.queue").build();
    }

    @Bean
    public Binding errorBinding(DirectExchange errorExchange, Queue errorQueue){
        return BindingBuilder.bind(errorQueue).to(errorExchange).with(SERVICE_NAME);
    }

    @Bean
    public MessageRecoverer messageRecoverer(){
        return new RepublishMessageRecoverer(rabbitTemplate, "error.direct", SERVICE_NAME);
    }
}
